//index.js
var cf = require("../../config.js");
var util = require("../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var searchHandle = require("../template/searchHandle.js");
var categoryTabHandle = require("../template/categoryTabWidget.js");
var baseHandle = require("../template/baseHandle.js");
var commHandle = require("../template/commHandle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, commHandle, searchHandle, categoryTabHandle,{

  /**
   * 页面的初始数据
   */
  data: {
    decoration: {},
    shoppingCartCount: 0,
    app: app,
    id: "",
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    bannerHeight: {},
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    playBgMusic: true,
    mallSiteId: "",
    haveSearch: false,
    showTaCard:false,
    hideCard:false,
    cardEmployee:{},
    touchStartY:0,
    touchEndY:0,
    promotionFlag:false,
    promotionResFlag:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    wx.showShareMenu({
      withShareTicket: false
    });
    //生命周期函数--监听页面加载
    var that = this;
    var pageId = options.pageId;
    that.setData({ 
      id: pageId,
      eId: options.eId || wx.getStorageSync("eId"),//为了保证有eid 所以使用 ||，进入微页面只有两种情况，一种 分享，一种通过名片步步点击进入
      shareSource: options.source
    });
    app.getUserInfo(this,options,function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      //说明是推广活动进来的
      var promotionId = options.promotionId;
      if (promotionId) {
        that.getPromotionData(promotionId, function (res) {
          that.setData({
            eId: res.data.model.result.employee.id,
            id: JSON.parse(res.data.model.result.commonPromotion.pageParam).pageId,
            promotionFlag: true,
            cardEmployee: res.data.model.result.employee
          })
          that.fetchData();
        })
      }
      //说明是通过分享进来的
      if (undefined !== that.data.shareSource && that.data.eId){
        util.addRelation(that.data.eId, cusmallToken, that.data.shareSource);
        that.queryCurCardDetail(that.data.eId, cusmallToken, function(res){
          var data = res.data;
          if(data && 0 == data.ret){
            that.setData({
              cardEmployee: data.model.employee,
              showTaCard:true
            })
          }
        });
      } else if (undefined !== that.data.shareSource){
        var companyInfo = wx.getStorageSync('companyInfo');
        that.setData({
          cardEmployee: {
            name: companyInfo.chName,
            headPic: that.data.userImagePath + companyInfo.headImg
          },
          showTaCard: true
        })
      }
      that.fetchData();
    });
  },
  search: function (e) {
    wx.navigateTo({
      url: '/pages/search/search?keyword=' + e.detail.value,
    })
  },
  //如果是推广活动进入 获取eid
  getPromotionData: function (promotionId, callback) {
    var that = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/commonpromotion/resolve',
      data: {
        cusmallToken: cusmallToken,
        promotionId: promotionId,
        page: '/pages/subCategory/subpage'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (0 == res.data.ret) {
          var eId = res.data.model.result.employee.id;
          util.addRelation(eId, cusmallToken, 0);
          that.setData({
            promotionEid: res.data.model.result.employee.id
          })
          callback && callback(res)
          wx.setStorageSync("eId", res.data.model.result.employee.id + "");
        }else{
          wx.showModal({
            title: '提示',
            content: '您访问的活动不存在',
            showCancel:false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
  loadNavPanelPageContent:function(){
    // 微页面里面不能使用标签导航
  },
  fetchData: function (hideLoading) {
    var that = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/cusmall_page/findById',
      data: {
        cusmallToken: cusmallToken,
        pageId: that.data.id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var decorationData = {};
        decorationData = JSON.parse(res.data.model.detail.decoration);

        var headerData = decorationData.header_data;
        util.processDecorationData(decorationData, that);
        // for (var i in decorationData.items) {
        //   var item = decorationData.items[i];
        // }
        that.setData({
          decoration: decorationData,
        });
        wx.setNavigationBarTitle({
          title: headerData.title || "微页面"
        });
        util.addBehaviorTrail(that.data.eId, 35, "", headerData.title);
        wx.hideLoading();
      }
    })
  },
  fetchLocationAddr: function (latitude, longitude) {
    var that = this;

    let multClassArr = that.data.multClassArr;
    let multInfoArr = {};
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        let submitData = {
          cusmallToken: cusmallToken,
          longitude: latitude || res.longitude,
          latitude: longitude || res.latitude
        };
        // 加载预览的店铺的多店铺信息
        if (app.globalData.previewuid) {
          submitData.uid = app.globalData.previewuid;
        }
        for (let key in multClassArr) {
            submitData.multClass = multClassArr[key];
            wx.request({
              url: cf.config.pageDomain + "/applet/mobile/multstore/getMultStoreList",
              data: submitData,
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                let data = res.data;
                if (data && data.model.result) {
                  that.setData({
                    ['multInfoArr.' + key + '']: data.model.result.slice(0, 5)
                  });

                } else {
                  that.setData({
                    ['multInfoArr.' + key + '']: []
                  });
                }

              },
              fail: function () {
              },
              complete: function () {
              }
            });
        }
      }
    })
  },
  navgateTap:function(){
    
  },
  getMultLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.fetchLocationAddr(res.latitude, res.longitude);
      }
    })
  },
  changeRoute: function (url) {
    wx.navigateTo({
      url: `../${url}/${url}`
    })
  },
  navTabFuc: function (e) {
    console.log(e);
    var url = e.currentTarget.dataset.url;
    if (!url) {
      return false;
    }
    if (url.indexOf("tel:") == 0) {
      wx.makePhoneCall({
        phoneNumber: url.split(":")[1]
      })
    }
  },
  zanTrigger:function(){
    
    let that = this;
    if (that.data.isThumbs){
      wx.showToast({
        title: "已经点过赞",
        icon: 'success',
        duration: 2000
      });
      return;
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/cusmall_page/thumbsUp",
      data: {
        cusmallToken: cusmallToken,
        id: that.data.id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data;
        if(data && 0 == data.ret){
          wx.showToast({
            title: "点赞成功",
            icon: 'success',
            duration: 2000
          });
          that.setData({
            isThumbs: true
          });
          that.setData({
            likeNum: that.data.likeNum + 1
          });
        }
      },
      fail: function () {
      },
      complete: function () {
      }
    });
  },
  toTACard(e){
    var ctx = this;
    if (ctx.data.eId){
      wx.reLaunch({
        url: '/pages/mycard/card?eId=' + ctx.data.eId,
      })
    }else{
      wx.reLaunch({
        url: 'pages/company_index/company_index'
      })

    }
    
    console.log("toTACard",e)
  },
  popTouchMove(e){
    console.log("popTouchMove", e);
    this.setData({
      touchEndY: e.touches[0].clientY
    });
  },
  popTouchStart(e){
    console.log("popTouchStart",e);
    this.setData({
      touchStartY: e.touches[0].clientY,
      touchEndY: e.touches[0].clientY
    });
  },
  popTouchEnd(e){
    var ctx = this;
    console.log("popTouchEnd", ctx.data.touchStartY, ctx.data.touchEndY );
    if (ctx.data.touchStartY - ctx.data.touchEndY > 25){
      ctx.setData({
        hideCard:true
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    util.getShoppingCartCount(function (count) {
      that.setData({ shoppingCartCount: count });
    }, app);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.audioCtx) {
      this.audioCtx.pause();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    app.getUserInfo(this,{},function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      // mallSiteId = wx.getStorageSync('mallSiteId');
      that.fetchData(true);
      util.getShoppingCartCount(function (count) {
        that.setData({ shoppingCartCount: count });
      }, app);
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {
    var ctx = this;
    //转发微页面
    util.addBehaviorTrail(ctx.data.eId, 36, "", ctx.data.decoration.header_data.title);
    var path = "/pages/subCategory/subpage?pageId=" + ctx.data.id + "&eId=" + ctx.data.eId +"&source=1";
    //path 添加客户来源
    path += "&fromOpenId=" + ctx.data.app.globalData.myOpenid + "&fromNickName=" + ctx.data.app.globalData.userInfo.nickName + "&forwardType=page_mpage";
      var shareObj = {
        title: this.data.decoration.header_data.title,
        path: path
      };
      return shareObj;
  }
}));